/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package myUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;

/**
 *
 * @author sony
 */
public class Utils
{
    public static String getSubstring(String originStr)
    {
        String s = originStr.length()>300?s="...":"";
        return originStr.substring(0, Math.min(300,originStr.length() ))+s;
    }

    public static String pswdConvert(String s)
    {
        HexBinaryAdapter adapter=new HexBinaryAdapter();
        byte[] temp=adapter.unmarshal(s);

        StringBuffer buffer=new StringBuffer();
        for(int i=0;i<temp.length;++i)
            buffer.append((char)temp[i]);

        return buffer.toString();
    }

    public static String pswdConvert(byte[] temp)
    {
         StringBuffer buffer=new StringBuffer();
        for(int i=0;i<temp.length;++i)
            buffer.append((char)temp[i]);

        return buffer.toString();
    }

    public static String getSHA1(String s) throws NoSuchAlgorithmException
    {
        try {
            MessageDigest alg = MessageDigest.getInstance("SHA-1");
            alg.update(s.getBytes());
            return pswdConvert(alg.digest());
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void getPreURL(HttpServletRequest request)
    {
        Cookie[] cookies=request.getCookies();
        for(int i=0;i<cookies.length;++i)
        {
            if(cookies[i].getName().equals(Constants.PRE_URL))
                request.setAttribute(Constants.PRE_URL, cookies[i].getValue());
        }
    }
}
